<template>
  <div>
    <a-table
      :dataSource="commentList"
      :columns="columns"
      :rowKey="
        (item) => {
          return item.id;
        }
      "
      :scroll="scroll"
    >
      <template slot="check" slot-scope="row">
        <p>{{ row }}</p>
      </template>
      <template slot="edit" slot-scope="row">
        <a-popconfirm
          title="确认删除该评论?"
          ok-text="确认"
          cancel-text="取消"
          @confirm="remove(row)"
        >
          <a-button icon="delete"></a-button>
        </a-popconfirm>
      </template>
    </a-table>
  </div>
</template>

<script>
export default {
  mounted() {
    this.getCommentList();
    if (document.body.clientWidth <= 1440) {
      this.scroll.x = 900;
    } else {
      this.scroll.x = 0;
    }
    const that = this;
    window.onresize = () => {
      return (() => {
        that.screenWidth = document.body.clientWidth;
      })();
    };
  },
  // 监听屏幕宽度改变
  watch: {
    /* 监听*/
    screenWidth(val) {
      if (val <= 1440) {
        this.scroll.x = 500;
      } else {
        this.scroll.x = 0;
      }
    },
  },
  data() {
    return {
      // 滚动条的配置
      scroll: {
        x: 0,
      },
      screenWidth: document.body.clientWidth, // 屏幕宽度
      // 评论列表
      commentList: [],
      columns: [
        {
          title: "评论人",
          dataIndex: "author",
          width: "10%",
        },
        {
          title: "文章标题",
          dataIndex: "title",
        },
        {
          title: "评论内容",
          dataIndex: "content",
          scopedSlots: { customRender: "check" },
          // 宽度
          width: "40%",
        },
        {
          title: "评论时间",
          dataIndex: "time",
          sorter: (a, b) =>
            new Date(a.time).getTime() - new Date(b.time).getTime(),
        },
        {
          title: "操作",
          scopedSlots: { customRender: "edit" },
        },
      ],
    };
  },
  methods: {
    // 获取评论列表
    getCommentList() {
      this.$axios.get("/api/comment/list.php").then((res) => {
        if (res.data.code === 1) {
          this.commentList = res.data.data;
          this.$message.success("获取评论成功!");
        } else {
          this.$message.error("获取评论失败");
        }
      });
    },
    // 删除指定评论
    remove({ id }) {
      this.$axios.post("/api/comment/remove.php", { id }).then((res) => {
        if (res.data.code === 1) {
          this.$message.success("删除评论成功!");
          this.getCommentList();
        } else {
          this.$message.error("删除评论失败!");
        }
      });
    },
  },
};
</script>

<style></style>
